import os
import sys
import random
import datetime
import time
import shutil

# 新版本占比
new_version_rate = 0.2

# 旧版本占比
old_version_rate = 0.3

# 其他地方导入的模型占比
existed_version_rate = 0.5

# 其他地方导入的模型文件路径
existed_version_models = ["../../backup"]

# 训练所得新版本模型文件保存路径
new_model_files = "./save/versions/new_version"

# 训练所得旧版本模型文件保存路径
old_model_files = "./save/versions/old_version"

# 定义新版本转化为旧版本的时间（单位：h）
time_from_newest_to_old = 3


def move_new_to_old():
    tmp = []
    # existed_models_path = []
    #
    # # 读入其他路径导入文件夹里的所有模型
    # for path in existed_version_models:
    #     for root, dirs, files in os.walk(path):
    #         if "saved_model.pb" in files:
    #             tmp.append((os.stat(root).st_ctime, root))
    #             existed_models_path = []

    # 读入目前新版本文件夹里的所有模型
    for root, dirs, files in os.walk(new_model_files):
        if "saved_model.pb" in files:
            if os.path.exists(root):
                tmp.append((os.stat(root).st_ctime, root))
    sorted_list = sorted(tmp, key=lambda x: (x[0], x[1]), reverse=True)

    # 根据时间将应该被划分为旧版本的文件筛选出来，转移到旧版本文件夹里面
    for model in sorted_list:
        if (sorted_list[0][0] - model[0]) / 3600 > time_from_newest_to_old:
            create_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(model[0]))
            if os.path.exists(model[1]):
                shutil.move(model[1], old_model_files + '/' + create_time + '/eval_policy')
    #
    # for model in existed_models_path:
    #     if(sorted_list[0][0] - model[0]) / 3600 <= time_from_newest_to_old:
    #         create_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(model[0]))
    #         shutil.move(model[1], new_model_files + '/' + create_time + '/eval_policy')


# 根据上述路径和百分比，选择一个现有的策略，并返回保存该策略的路径，用于env_constructor()
def generate_enemy_policy():
    # print("ENTER GENETATION")
    existed_models_path = []
    old_models_path = []
    new_models_path = []

    # 调整新旧版本文件
    # move_new_to_old()

    # 读入其他路径导入的模型
    for path in existed_version_models:
        for root, dirs, files in os.walk(path):
            if "saved_model.pb" in files:
                if os.path.exists(root):
                    existed_models_path.append(root)

    # 读入新版本模型的路径
    for root, dirs, files in os.walk(new_model_files):
        if "saved_model.pb" in files:
            if os.path.exists(root):
                new_models_path.append((os.stat(root).st_ctime, root))
    new_models_path = sorted(new_models_path, key=lambda x: (x[0], x[1]), reverse=True)

    # 读入旧版本模型的路径
    for root, dirs, files in os.walk(old_model_files):
        if "saved_model.pb" in files:
            if os.path.exists(root):
                old_models_path.append(root)

    rand = random.random()
    if rand < new_version_rate:
        if os.path.exists(new_models_path[0][1]):
            print("env_constructed with new_version")
            return new_models_path[0][1]

    if len(old_models_path) > 0 and new_version_rate <= rand < new_version_rate + old_version_rate:
        idx = random.randint(0, len(old_models_path) - 1)
        print("env_constructed with old_version")
        if os.path.exists(old_models_path[idx]):
            return old_models_path[idx]

    if len(existed_models_path) > 0:
        print("env_constructed with existed_version")
        idx = random.randint(0, len(existed_models_path) - 1)
        if os.path.exists(existed_models_path[idx]):
            return existed_models_path[idx]


if __name__ == '__main__':
    print("start")
    for i in range(50):
        print(generate_enemy_policy())
